<?php


namespace app\api\service;


use app\common\model\User;
use app\common\model\UserWithdrawalLog;
use app\common\model\UserDistribution;
use think\Db;
use think\Config;
use think\Exception;
use services\GetuiService;
use services\AlipayService;
use services\WxwithdrawalService;
use app\common\model\UserLuckdrawLog;
use think\Cache;

class UserService
{
    public function addWithdrawalLog($user, $wallet, $desc = '', $extend = [])
    {
        Db::startTrans();
        try {
            $before = $user->beans;
            $after = bcsub($before, $wallet,2);
            $data = [
                'log_mod' => $extend['log_mod'],
                'card_no' => $extend['card_no'],
                'real_name' => $extend['real_name'],
                'withdrawal_no' => $extend['withdrawal_no'],
                'user_id' => $user->id,
                'log_type' => 1,
                'wallet' => $wallet,
                'before_wallet' => $before,
                'after_wallet' => $after,
                'with_time' => time(),
                'with_desc' => $desc,
                'log_status' => 0,
                'is_merchant' => 2
            ];
            $log = UserWithdrawalLog::create($data);
            if (!$log) {Db::rollback();return false;}
            $beans = -1*$wallet;
            $res = (new User())->beans($beans, $user->id, '吃豆提现', $log['id']);
            if (!$res) {Db::rollback();return false;}
            // 如果是限制用户，需要后台审核通过
            // if (!$user['is_limited']) {
                if ($log['log_mod']=='alipay') {
                    // 转账操作
                    $param = [
                        'out_biz_no' => $log['withdrawal_no'],
                        'trans_amount' => $log['wallet'],
                        'order_title' => '吃喝不愁外卖试吃返利提现',
                        'payee_info' => [
                            'identity_type' => 'ALIPAY_LOGON_ID',
                            'identity' => $log['card_no'],
                            'name' => $log['real_name']
                        ],
                    ];
                    $AlipayService = new AlipayService();
                    $response = $AlipayService->transfer($param);
                    // var_dump($response);exit;
                    //object(stdClass)#37 (7) { ["code"]=> string(5) "10000" ["msg"]=> string(7) "Success" ["order_id"]=> string(32) "20230426020070011500710076889748" ["out_biz_no"]=> string(8) "43545676" ["pay_fund_order_id"]=> string(32) "20230426020070011500710076889748" ["status"]=> string(7) "SUCCESS" ["trans_date"]=> string(19) "2023-04-26 15:24:58" }
                    if(!empty($response->code)&&$response->code==10000){
                        // 审核通过
                        $result = $log->allowField(true)->save([
                            'log_status' => 1,
                            'handel_admin_id' => $user->id,
                            'handel_time' => time(),
                            'batch_id' => $response->pay_fund_order_id,
                        ]);

                    }else{
                        Db::rollback();
                        $error = isset($response->sub_msg)?$response->sub_msg:'转账失败';
                        return ['status'=>0 ,'msg'=>$error];
                    }
                } else {
                    // 获取公钥
                    $WxwithdrawalService = new WxwithdrawalService();
                    $publickey = Cache::get('publickey');
                    if (!$publickey) {
                        // 获取微信证书
                        $res = $WxwithdrawalService->certificates();
                        $certificates = json_decode($res,1);
                        $Aes = new \fast\AesUtil(config('xcx.mch_key'));
                        $associatedData = $certificates['data'][0]['encrypt_certificate']['associated_data'];
                        $nonceStr = $certificates['data'][0]['encrypt_certificate']['nonce'];
                        $ciphertext = $certificates['data'][0]['encrypt_certificate']['ciphertext'];
                        // 解析公钥
                        $publickey = $Aes->decryptToString($associatedData, $nonceStr, $ciphertext); 
                        Cache::set('publickey',$publickey,86400);
                    }
                    $unionid = User::where('id',$log['user_id'])->value('unionid');
                    if ($_SERVER['HTTP_PLATFORM']=='wxMiniProgram') {
                        $appid=config('xcx.appid');
                        $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'miniprogram','user_id'=>$user->id])->value('openid');
                    } else {
                        $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'h5','user_id'=>$user->id])->value('openid');
                        $appid=config('wx_gzh.appid');
                        if (!$openid) {
                            $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'miniprogram','user_id'=>$user->id])->value('openid');
                            $appid=config('xcx.appid');
                        }
                    }
                    if (!$openid) {
                        return ['status'=>0 ,'msg'=>'无法获得授权，请联系客服处理！'];
                    }
                    //请求参数,大于0.3要传姓名
                    if ($log['wallet']<0.3 || $extend['real_name']=='SHEE KAI YING' || $extend['real_name']=='JCHANGLOCK') {
                        $data = [
                            'appid'=>$appid,
                            'out_batch_no'=>strval($log['withdrawal_no']),
                            'batch_name' => '吃喝不愁外卖试吃返利提现',
                            'batch_remark' => '吃喝不愁外卖试吃返利提现',
                            'total_amount' => intval(strval($log['wallet']*100)),
                            'total_num' => 1,
                            'transfer_detail_list'=>[[
                                'out_detail_no' => strval($log['withdrawal_no']),
                                'transfer_amount'=>intval(strval($log['wallet']*100)),
                                'transfer_remark'=>'吃喝不愁外卖试吃返利提现',
                                'openid' => $openid,
                            ]],
                            'notify_url' => config('domain').'/index/yunzhan/txNotify'
                        ];
                    } else {
                        $data = [
                            'appid'=>$appid,
                            'out_batch_no'=>strval($log['withdrawal_no']),
                            'batch_name' => '吃喝不愁外卖试吃返利提现',
                            'batch_remark' => '吃喝不愁外卖试吃返利提现',
                            'total_amount' => intval(strval($log['wallet']*100)),
                            'total_num' => 1,
                            'transfer_detail_list'=>[[
                                'out_detail_no' => strval($log['withdrawal_no']),
                                'transfer_amount'=>intval(strval($log['wallet']*100)),
                                'transfer_remark'=>'吃喝不愁外卖试吃返利提现',
                                'openid' => $openid,
                                'user_name' => $WxwithdrawalService->getEncrypt($extend['real_name'],$publickey),
                            ]],
                            'notify_url' => config('domain').'/index/yunzhan/txNotify'
                        ];
                    }
                    $res = $WxwithdrawalService->transfer($data);
                    if(!isset($res['create_time'])) {//批次受理失败
                        Db::rollback();
                        return false;
                    } else {
                        // 审核通过
                        $result = $log->allowField(true)->save([
                            'log_status' => 1,
                            'handel_admin_id' => $user->id,
                            'handel_time' => time(),
                            'batch_id' => $res['batch_id'],
                        ]);
                    }
                }

                // 发送app消息
                $user = \app\common\model\User::get($log['user_id']);
                // if (isset($user['birthday']) && $user['birthday']) {
                    $lPublics = new \app\api\service\UserService();
                    $title = '吃豆提现成功';
                    $desc = '恭喜您，成功提现'.$log['wallet'].'吃豆';
                    $url = '/pages/user/user-data';
                    $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                // }
            // }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public function getLocationWxGroup($lat, $lng,$type)
    {
        $field = "*,round((6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000)/1,1) as distance";
        $map = [
            'status' => ['=', '1'],
        ];
        $map['type'] = $type;
        $list = Db::name('wechat_group')
            ->field($field)
            ->where($map)
            ->order('distance asc,id desc')
            ->limit(0, 10)
            ->select();
        return $list;
    }

    /**
     * 分销奖励
     * @DateTime 2023-04-25T15:13:39+0800
     * @param    [type]                   $order_nos [description]
     * @return   [type]                              [description]
     */
    public function userDistribution($order_nos)
    {
        Db::startTrans();
        try {
            foreach ($order_nos as $key => $value) {
                $UserDistribution = UserDistribution::where(['play_order_no'=>$value,'status'=>0])->find();
                if ($UserDistribution) {
                    // 上级用户加吃豆
                    $res = (new User())->beans($UserDistribution['amount'], $UserDistribution['pid'], '下级返利', $UserDistribution['play_order_no']);
                    if (!$res) {Db::rollback();return false;}
                    $UserDistribution->status = 1;
                    $UserDistribution->save();
                    // 发送app消息
                    $user = \app\common\model\User::get($UserDistribution['pid']);
                    $user1 = \app\common\model\User::get($UserDistribution['uid']);
                    // if (isset($user['birthday']) && $user['birthday']) {
                        $lPublics = new \app\api\service\UserService();
                        $title = '团长奖励获得吃豆';
                        $desc = '您的好友'.$user1['nickname'].'完成第'.$UserDistribution['order_times'].'单，奖励您'.$UserDistribution['amount'].'吃豆';
                        $url = '/pages/user/user-data';
                        $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id']);
                    // }
                }
            }
            
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            \think\Log::write($e->getMessage());
            return false;
        }
    }



    //个推消息推送
    public function pushChat($cid,$title,$content,$path,$user_id=0,$play_order_no=0)
    {
        if(empty($title) || empty($content) || empty($path)){
            die;
        }
        $res = [];
        if ($cid) {
            $getui = new GetuiService();
            //单发测试 $cid 客户端id 前端获取
            $res = $getui->pushMessageToSingle($cid,$title,$content,$path);
            //{ ["result"]=> string(2) "ok" ["taskId"]=> string(41) "OSS-0510_ed39c8f429c55501c4ed62b743fdd7d6" ["status"]=> string(16) "successed_online" }
            // var_dump($res);exit;
            $res['cid'] = $cid;
        }
        Db::name('notice')->insertGetId([
            'type' => 3,
            'title' => $title,
            'content' => $content,
            'play_order_no'=>$play_order_no,
            'user_id'=>$user_id,
        ]);
        \think\Log::write('app推送'.json_encode($res));
        return $res;
    }


    public function qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user_id=0)
    {
        return true;
        include_once ROOT_PATH."extend/weworkapi/api/src/CorpAPI.class.php";
        $corpid= config('qywx.corpid');
        $corpsecret= config('qywx.secret');
        $api = new \CorpAPI($corpid, $corpsecret);
        $token = $api->obtainAccessToken();
        $qurl = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token='.$token;
        $sender = 'DanDandea';
        $param = [
            'chat_type' => 'single',
            'external_userid' => $external_userid,
            'sender' => $sender,
            'allow_select' => false,
            'attachments' =>[[
                'msgtype' => 'link',
                'link' => [
                    'title' => $title,
                    'picurl' => $picurl,
                    'desc' => $desc,
                    'url' => $url,
                ],
            ]],
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        $res = \fast\Http::post($qurl,$params,[],$header);
        Db::name('notice')->insertGetId([
            'type' => 2,
            'title' => $title,
            'user_id' => $user_id,
            'content' => $desc,
        ]);
        return $res;
    }

    /**
     * 黑名单核验
     * @DateTime 2023-06-02T21:45:19+0800
     * @param    [type]                   $user_id 用户id
     * @param    [type]                   $info    需核验的信息
     * @param    [type]                   $type    类型1-电话拉黑2-关键字3-支付宝账号
     */
    public function setBlackList($user_id,$info,$type)
    {
        Db::startTrans();
        $one = Db::name('blacklist_item')->where(['type'=>$type,'content'=>$info])->find();
        try {
            if ($one) {
                $user = User::where('id',$user_id)->find();
                $all = [];
                if ($one['reason']=='拉黑') {
                    $user->status = 'hidden';
                    $user->updatetime = time();
                    $user->save();
                    $all['mode'] = 1;
                } else {
                    $user->is_limited = 1;
                    $user->updatetime = time();
                    $user->save();
                    $all['mode'] = 2;
                }
                $all['blacklist_id'] = $one['blacklist_id'];
                $all['user_id'] = $user_id;
                $all['type'] = $one['type'];
                $all['reason'] = $one['reason'];
                $all['content'] = $one['content'];
                $all['status'] = 1;
                Db::name('blacklist_item')->insertGetId($all);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }



    public function oneLevel($user_id)
    {
        Db::startTrans();
        try {
            $memo = '加福利群';
            $num = 2;
            $count = UserLuckdrawLog::where(['type'=>1,'user_id'=>$user_id,'memo'=>$memo])->count();
            if (!$count) {
                $data = [
                    'user_id' => $user_id,
                    'type' => 1,
                    'memo' => $memo,
                    'trans_no' => 0,
                    'num' => $num,
                    'date' => date('Ymd'),
                ];
                UserLuckdrawLog::create($data);
                $user = User::get($user_id);
                $user->luckdraw_num = $user->luckdraw_num+$num;
                if ($user->level==0) {
                    $user->level = 1;
                }
                $user->save();
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }


    /**
     * [xcxNotice description]
     * @param  [type] $openid [description]
     * @param  [type] $data   [description]
        $thing1="商品名称";//商品名称
        $time3="2024-03-15 20:47:00";//完成时间
        $character_string5="4535146543";//订单号
        $phrase10="订单状态";//订单状态
        $data = [
            'thing1' => ['value'=>$thing1],
            'time3' => ['value'=>$time3],
            'character_string5' => ['value'=>$character_string5],
            'phrase10' => ['value'=>$phrase10],
        ];
     */
    public function xcxNotice($openid,$template_id,$page,$data)
    {
        $appid = Config::get('xcx.appid');
        $appSecret = Config::get('xcx.appsecret');
        $access_token = (new \app\api\service\BaseService())->xcxAccessToken($appid,$appSecret);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        $postdata = [
            'access_token' => $access_token,
            'template_id' => $template_id,
            'page' => $page,
            'touser' => $openid,
            'data' => $data,
            'miniprogram_state' => 'formal',
        ];
        $params = json_encode($postdata);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        $res = \fast\Http::post($url,$params,[],$header);
        \think\Log::write('订阅消息'.$res);
        return $res;
    }
}